## Function to estimate AMCEs

estimate_AMCEs <- function(title, data, model, weights = FALSE) {
  
  df <- data
  subjects <- deparse(substitute(data))

  if (weights == FALSE){
    set_weights = NULL
  } else if (weights == TRUE) {
    set_weights = "weight"
  }
  
  attribute_list <- parameters[[1]]
  baselines <- parameters[[2]]
  marginal_weights <- parameters[[3]]
  
  names.only <- do.call("rbind", lapply(attribute_list, as.data.frame))
  names(names.only)[1] <- "Level"
  names.only$Attribute <- rownames(names.only)
  names.only$Attribute <- sub(".\\d+", "", names.only$Attribute)
  names.only$Level <- as.character(names.only$Level)
  
  attributes.only <- names.only %>% 
    dplyr::select(Attribute) %>% 
    distinct()
  
  design <- makeDesign(type = "constraints",
                           attribute.levels = attribute_list,
                           constraints = constraint_list,
                           level.probs = marginal_weights)
  
  results <- amce(model,
                  data = df,
                  cluster = TRUE,
                  respondent.id = "id",
                  design = design,
                  baselines = baselines,
                  weights = set_weights)
  
  results.summary <- summary(results)
  N <- results.summary$respondents

  out <- results.summary$amce %>%
    select(Attribute, Level, Estimate, `Std. Err`) %>%
    merge(names.only, all = TRUE) %>%
    bind_rows(attributes.only) %>%
    arrange(Attribute, Level) %>%
    mutate(p_raw = 2 * pnorm(-abs(`Estimate`/`Std. Err`)),
           upper = Estimate + 1.96 * `Std. Err`,
           lower = Estimate - 1.96 * `Std. Err`,
           sig = (p_raw < 0.05),
           #data = subjects,
           nobs = N,
           order = order_attributes_levels(Attribute, Level)
    ) %>%
    arrange(order) %>%
    mutate(var.names = paste0(Attribute, ":"),
           var.names = ifelse(!is.na(Level) & is.na(Estimate), paste0("   ", Level, " (Baseline)"), var.names),
           var.names = ifelse(!is.na(Estimate), paste0("   ", Level), var.names))

  write_csv(out, paste0("figures/_csv/", title, ".csv"))

  return(out)

}
